<?php

namespace app\api\controller\Appoint;

use app\api\controller\Common;
use app\api\Logic\Campusclass\CampusClassCourseSignLogic;
use app\api\Logic\Campusclass\CampusClassDateRecordLogic;
use app\api\Logic\Campusclass\ClassCourseLogic;
use app\api\Logic\ManystoreShopSettingLogic;
use app\api\model\CampusClassCourseSignModel;
use app\api\model\CampusClassDateRecordModel;
use think\Db;
use think\Exception;
use think\exception\DbException;

/**
 * 学员约课记录
 */
class CourseSign extends Common
{
    protected $noNeedLogin = ['*'];

    protected $campusClassCourseSignLogic;
    protected $manystoreShopSettingLogic;
    protected $campusClassDateRecordLogic;
    protected $classCourseLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->campusClassCourseSignLogic = new CampusClassCourseSignLogic();
        $this->manystoreShopSettingLogic = new ManystoreShopSettingLogic();
        $this->campusClassDateRecordLogic = new CampusClassDateRecordLogic();
        $this->classCourseLogic = new ClassCourseLogic();
    }

    /**
     * 返回学员预约记录
     * @throws DbException
     */
    public function list(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            //获取学员预约记录
            $list = CampusClassCourseSignModel::where('user_id',$params['user_id'])
                ->where('status',0)
                ->with([
                    'classInfo' => function ($query) {
                        $query->withField('id,name');
                    },
                    'classRoom' => function ($query) {
                        $query->withField('id,name');
                    },
                    'teacherInfo' => function ($query) {
                        $query->withField('id,username,nickname')
                            ->where('level',2);
                    },
                    'userInfo' => function ($query) {
                        $query->withField('id,truename');
                    }
                ])
                ->field('id,a_id,d_id,user_id,class_id,week,start_time,start_time_txt,end_time,end_time_txt,teacher_id,classroom_id,status')
                ->order('create_time','desc')
                ->paginate(PAGE_SIZE);
            $list = objToArray($list) ?? [];

            if(!empty($list)){
                $this->success('查询成功',$list);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 取消预约
     */
    public function cancel(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $signId = $params['sign_id'] ?? 0;
            if(!$signId){
                $this->error('预约记录ID必须');
            }

            $signInfo = $this->campusClassCourseSignLogic->getInfo($signId);
            if(empty($signInfo)){
                $this->error('预约记录不存在');
            }

            //是否允许取消预约
            $isCanCancel = $this->manystoreShopSettingLogic->cancelVerifyRule($params['shop_id'],$signInfo);
            if(!$isCanCancel){
                $this->error('该记录不可取消预约');
            }

            Db::startTrans();
            try {
                //取消预约
                $this->campusClassCourseSignLogic->cancel($signId);
                //让最近一位排队的学员插入到预约记录中
                //查询排队在最前列的排队记录
                $oldestInfo = $this->campusClassDateRecordLogic->getOldestInfo($signInfo['d_id']);
                if(!empty($oldestInfo)){
                    //根据班课ID获取班级课表
                    $dateInfo = $this->classCourseLogic->getInfo($signInfo['d_id']);
                    //添加预约成功记录
                    $this->campusClassCourseSignLogic->insert([
                        'a_id' => $dateInfo['a_id'],
                        'd_id' => $dateInfo['id'],
                        'user_id' => $oldestInfo['user_id'],
                        'class_id' => $dateInfo['class_id'],
                        'record_id' => $oldestInfo['id'],
                        'week' => $dateInfo['week'],
                        'start_time' => $dateInfo['start_time'],
                        'end_time' => $dateInfo['end_time'],
                        'teacher_id' => $dateInfo['teacher_id'],
                        'classroom_id' => $dateInfo['classroom_id']
                    ]);

                    //修改排队记录为已约上
                    CampusClassDateRecordModel::where('id',$oldestInfo['id'])
                        ->update(['status' => 1]);
                }

                Db::commit();
                $this->success('取消成功');
            }catch (Exception $e){
                Db::rollback();
                $this->error('取消失败');
            }
        }
        $this->error('请求错误');
    }
}
